<?php
$loader->requireOnce('ordo/Ticket.class.php');
/**
 * Object Relational Persistence Mapping Class for table: patient
 *
 * @package	com.clearhealth
 * @author	ClearHealth Inc.
 */
class Patient extends ORDataObject {

    /**#@+
     * Fields of table: patient mapped to class members
     */
    var $person_id	= '';
    var $patient_code		= '';
    var $relative_name		= '';
    var $relative_address	= '';
    var $relative_number	= '';
    var $last_exam			= '';

    /**#@-*/


    /**
     * DB Table
     */
    var $_table = 'patient';

    /**
     * Primary Key
     */
    var $_key = 'person_id';

    /**
     * Internal Name
     */
    var $_internalName = 'Patient';

    /**
     * Handle instantiation
     */
    function Patient() {
        parent::ORDataObject();
    }

    function setup($id = 0) {
        $this->set_id($id);
        if ($id > 0) {
            $this->populate();
        }
    }

    function populate() {
        parent::populate('person_id');
    }

    function set_id($id) {
        $this->person_id = $id;
    }

    public function genCode() {
        $seq = $this->_db->genId('patient_code_sequences');
        return $seq;
    }

    public function setPatientId($id){
        $this->person_id=$id;
    }

    public function getPatientCode(){
        return $this->patient_code;
    }

    public function getRelativeName(){
        return $this->relative_name;
    }

    public function getRelativeNumber(){
        return $this->relative_number;
    }

    public function getRelativeAddress(){
        return $this->relative_address;
    }

    public function searchPatientByName($name) {
        $ds =& new Datasource_sql();
        $sql = array(
            'cols'     => "p.person_id, p.name, p.date_of_birth, p.phone_number, p1.patient_code",
            'from'     => "person p INNER JOIN patient p1 ON
            			(p.person_id=p1.person_id AND name LIKE '%". $name ."%')",
            'orderby'  => 'p.name',
            'limit'    => 50
        );
        $ds->setup($this->_db,$sql);
        $result = $ds->toArray();
        if (!empty($result)) {
            foreach ($result as &$item) {
            	$item['date_of_birth_formatted'] = L10nHelper::renderDateTime($item['date_of_birth']);
            }
        }
        return $result;
    }

    public function getPatientIdByPatientCode($patientCode) {
        $ds =& new Datasource_sql();
        $patientCode = str_pad($patientCode, 6, "0", STR_PAD_LEFT);
        $sql = array(
            'cols'     => "person_id",
            'from'     => "patient",
            'where'    => "patient_code='$patientCode'"
        );
        $ds->setup($this->_db,$sql);
        $result = $ds->toArray();
        if (empty($result)) {
            return null;
        }
        return $result[0]['person_id'];
    }

    public function isExist($patientId) {
        $sql = "select person_id from patient where person_id = $patientId";
        $res = $this->_execute($sql);
        if ($res && !$res->EOF) {
            return true;
        }
        return false;
    }

    public function getLastExamDate() {
        if ($this->last_exam == '' || $this->last_exam == '0000-00-00 00:00:00') {
            return L10nHelper::_('Not updated');
        }
        return L10nHelper::renderDateTime($this->last_exam);
    }

    public function getInfoForCostStatisticReport($startDate, $endDate, $fromHCM=true, $insuranceType='required'){
        $ds = new Datasource_sql();
        $sql[ 'orderby']	=	"encounter_date";
        $sql['from']	=	"ticket t LEFT JOIN $this->_table pa ON t.patient_id=pa.person_id
			LEFT JOIN person p ON pa.person_id=p.person_id
		   	LEFT JOIN insurance i ON p.person_id=i.patient_id
		   	LEFT JOIN hospital h ON i.registered_hospital_id = h.hospital_id
		   	LEFT JOIN address ad ON p.address_id = ad.address_id";

        // Faco department
        $sql['cols']	=	"t.department_id, pa.patient_code, p.name, i.insurance_code, h.name hospital, DATE_FORMAT(t.created,'%d/%m/%Y') encounter_date, 'Phaco&IOL' as diagnosis";
        $sql['where']	=	"'$startDate' <= DATE(t.created) AND DATE(t.created) <= '$endDate'".
		    				" AND t.status='". Ticket::CLOSED_STATUS. "'".
		    				" AND t.insurance='$insuranceType'";
        if($fromHCM){
            $sql['where']	.=	" AND ad.province_id = ".Province::HCM_PROVINCE_ID;
        }
        else{
            $sql['where']	.=	" AND ad.province_id != ".Province::HCM_PROVINCE_ID;
        }
        $ds->setup($this->_db, $sql);
        $res	=	$ds->toArray();
        return $res;
    }

    function deletePatient($patientId) {
    	$sql = "DELETE FROM $this->_table WHERE $this->_key = '$patientId'";
    	$res	=	$this->_execute($sql);
    	if ($res === false) {
   			return $res;
   		}
    	$res	=	Celini::newORDO('Person')->deletePerson($patientId);
        if ($res === false) {
            return $res;
        }
        $res    =   Celini::newORDO('Insurance')->delete($patientId);
    	return $res;
    }

    /**
     * Check if a patient exist for a given code.
     *
     * @param mixed $patientCode Patient code
     * @return bool
     */
    public function checkPatientByCode($patientCode) {
        $sql = "SELECT person_id FROM patient WHERE patient_code = '$patientCode'";
        $res = $this->_execute($sql);
        if ($res && !$res->EOF) {
            return $res->fields['person_id'];
        }
        return false;
    }
}
?>
